<template>
  <div class="transaction-upload">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>上传账单</span>
        </div>
      </template>

      <div class="upload-container">
        <el-upload ref="upload" class="upload-demo" drag action="#" :auto-upload="false" :on-change="handleFileChange"
          :on-preview="handleFilePreview" :on-remove="handleFileRemove" :file-list="fileList" multiple>
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">
            支持上传Excel、CSV等格式文件，单个文件不超过10MB
          </div>
        </el-upload>

        <!-- 将上传按钮移出upload组件，确保点击事件能正确触发 -->
        <div style="text-align: center; margin-top: 20px;">
          <el-button style="margin-left: 10px;" type="success" @click="submitUpload" :loading="loading" :disabled="loading">上传文件</el-button>
        </div>

        <div v-if="uploadResult" class="upload-result">
          <el-divider>上传结果</el-divider>
          <el-alert :title="uploadResult.success ? '上传成功' : uploadResult.data?.some(item => item.status === '成功') ? '部分成功' : '上传失败'" 
            :type="uploadResult.success ? 'success' : uploadResult.data?.some(item => item.status === '成功') ? 'warning' : 'error'"
            :description="uploadResult.message" show-icon></el-alert>
            
          <!-- 详细统计信息 -->
          <el-card v-if="uploadResult.summary" class="result-summary" shadow="hover">
            <div slot="header" class="clearfix">
              <span>处理统计</span>
            </div>
            <div class="summary-content" v-html="uploadResult.summary.replace(/\n/g, '<br>')"></div>
          </el-card>
          
          <!-- 详细处理记录 -->
          <el-table v-if="uploadResult.data && uploadResult.data.length > 0" :data="uploadResult.data"
            style="width: 100%; margin-top: 20px;">
            <el-table-column prop="rowNum" label="序号" width="80"></el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template slot-scope="scope">
                <el-tag :type="getStatusTagType(scope.row.status)">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="message" label="信息"></el-table-column>
          </el-table>
          
          <!-- 重复记录详情（如果有） -->
          <el-card v-if="uploadResult.details && uploadResult.details.duplicateCount > 0" class="duplicate-details" shadow="hover">
            <div slot="header" class="clearfix">
              <span>重复记录详情</span>
            </div>
            <div v-if="uploadResult.details.duplicateRecords">
              <div v-for="(duplicates, fileName) in uploadResult.details.duplicateRecords" :key="fileName" class="duplicate-file-section">
                <h4>{{ fileName }} (共 {{ duplicates.length }} 条重复记录)</h4>
                <el-collapse v-if="Array.isArray(duplicates) && duplicates.length > 0">
                  <el-collapse-item :title="`显示重复记录详情`" name="1">
                    <div v-for="(record, index) in duplicates" :key="index" class="duplicate-item">
                      {{ record }}
                    </div>
                  </el-collapse-item>
                </el-collapse>
              </div>
            </div>
          </el-card>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { transactionService } from '@/api/transactionService'

export default {
  name: 'TransactionUpload',
  data() {
    return {
      fileList: [],
      uploadResult: null,
      loading: false
    }
  },
  methods: {
    handleFileChange(file, fileList) {
      console.log('File changed:', file.name, fileList.length)
      this.fileList = fileList
    },

    handleFilePreview(file) {
      console.log('File preview:', file)
    },

    handleFileRemove(file, fileList) {
      console.log('File removed:', file.name)
      this.fileList = fileList
    },


    submitUpload() {
      console.log('Submit upload clicked, fileList length:', this.fileList.length)

      if (this.fileList.length === 0) {
        this.$message.warning('请先选择要上传的文件')
        return
      }

      // 设置加载状态
      this.loading = true
      this.uploadResult = null

      // 验证所有文件
      const validFiles = []
      const invalidFiles = []
      
      for (const file of this.fileList) {
        if (this.beforeUpload(file.raw)) {
          validFiles.push(file.raw)
        } else {
          invalidFiles.push(file.name)
        }
      }

      if (validFiles.length === 0) {
        this.$message.error('所有文件验证失败，请检查文件格式和大小')
        this.loading = false
        return
      }

      // 创建FormData，添加所有有效文件
      const formData = new FormData()
      validFiles.forEach(file => {
        formData.append('files', file)
      })

      console.log('Uploading files:', validFiles.map(f => f.name).join(', '))

      // 一次性上传所有文件
      transactionService.uploadFile(formData)
        .then(response => {
          console.log('Upload success:', response)
          this.handleUploadSuccess(response.data)
        })
        .catch(error => {
          console.error('Upload error:', error)
          this.handleUploadError(error)
        })
        .finally(() => {
          // 恢复加载状态
          this.loading = false
        })
    },

    getStatusTagType(status) {
      switch (status) {
        case '成功':
          return 'success'
        case '失败':
          return 'danger'
        case '跳过':
          return 'warning'
        default:
          return 'info'
      }
    },
    
    beforeUpload(file) {
      // 检查文件类型
      const validTypes = ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'text/csv']
      const validExtensions = ['.xls', '.xlsx', '.csv']

      const isValidType = validTypes.includes(file.type)
      const isValidExtension = validExtensions.some(ext => file.name.endsWith(ext))

      if (!isValidType && !isValidExtension) {
        this.$message.error('只支持Excel和CSV格式文件！')
        return false
      }

      // 检查文件大小
      const maxSize = 10 * 1024 * 1024 // 10MB
      if (file.size > maxSize) {
        this.$message.error('文件大小不能超过10MB！')
        return false
      }

      return true
    },
    handleUploadSuccess(response) {
      // 添加空值检查，防止response为undefined时出错
      const message = response && response.message ? response.message : '文件上传成功！'
      this.$message.success(message)
      // 使用实际的后端返回数据构建更详细的结果
      const resultData = []
      
      // 添加成功文件信息
      if (response && response.successFiles && response.successFiles.length > 0) {
        response.successFiles.forEach(fileName => {
          resultData.push({
            rowNum: resultData.length + 1,
            status: '成功',
            message: `文件 ${fileName} 处理成功`
          })
        })
      }
      
      // 添加失败文件信息
      if (response && response.errorFiles && response.errorFiles.length > 0) {
        response.errorFiles.forEach(errorMsg => {
          resultData.push({
            rowNum: resultData.length + 1,
            status: '失败',
            message: errorMsg
          })
        })
      }
      
      // 添加重复记录信息
      let duplicateCount = 0
      if (response && response.duplicateRecords) {
        const fileKeys = Object.keys(response.duplicateRecords)
        if (fileKeys.length > 0) {
          fileKeys.forEach(fileName => {
            const duplicates = response.duplicateRecords[fileName]
            if (Array.isArray(duplicates) && duplicates.length > 0) {
              // 添加该文件的重复记录总数信息
              resultData.push({
                rowNum: resultData.length + 1,
                status: '跳过',
                message: `文件 ${fileName} 中发现 ${duplicates.length} 条重复记录`
              })
              // 更新重复记录总数
              duplicateCount += duplicates.length
            }
          })
        }
      }
      
      // 构建详细的统计信息
      let summary = `共处理 ${response ? response.totalFiles || 0 : 0} 个文件，${response ? response.successCount || 0 : 0} 个成功，${response ? response.errorCount || 0 : 0} 个失败`
      if (response && response.totalRecords > 0) {
        summary += `\n共 ${response.totalRecords} 条记录，成功保存 ${response.totalSavedCount} 条`
        if (duplicateCount > 0) {
          summary += `，跳过重复记录 ${duplicateCount} 条`
        }
      }
      
      this.uploadResult = {
        success: true,
        message: response.message || '文件上传成功',
        summary: summary,
        data: resultData,
        details: {
          totalFiles: response.totalFiles,
          successCount: response.successCount,
          errorCount: response.errorCount,
          totalRecords: response.totalRecords,
          totalSavedCount: response.totalSavedCount,
          duplicateRecords: response.duplicateRecords,
          duplicateCount: duplicateCount
        }
      }
    },
    handleUploadError(error) {
      let errorMessage = '文件上传失败，请检查文件格式和网络连接'
      let errorData = []
      
      // 尝试从错误响应中提取有用信息
      if (error.response && error.response.data) {
        const responseData = error.response.data
        errorMessage = responseData.error || responseData.message || errorMessage
        
        // 构建更详细的错误数据，包括可能的成功和失败文件信息
        const resultData = []
        
        // 如果有成功文件，也显示出来
        if (responseData.successFiles && responseData.successFiles.length > 0) {
          responseData.successFiles.forEach(fileName => {
            resultData.push({
              rowNum: resultData.length + 1,
              status: '成功',
              message: `文件 ${fileName} 处理成功`
            })
          })
        }
        
        // 添加失败文件信息
        if (responseData.errorFiles && responseData.errorFiles.length > 0) {
          responseData.errorFiles.forEach(errorMsg => {
            resultData.push({
              rowNum: resultData.length + 1,
              status: '失败',
              message: errorMsg
            })
          })
        }
        
        // 添加重复记录信息
      if (responseData.duplicateRecords) {
        const fileKeys = Object.keys(responseData.duplicateRecords)
        if (fileKeys.length > 0) {
          fileKeys.forEach(fileName => {
            const duplicates = responseData.duplicateRecords[fileName]
            if (Array.isArray(duplicates) && duplicates.length > 0) {
              // 添加该文件的重复记录总数信息
              resultData.push({
                rowNum: resultData.length + 1,
                status: '跳过',
                message: `文件 ${fileName} 中发现 ${duplicates.length} 条重复记录`
              })
            }
          })
        }
      }
        
        errorData = resultData
        
        // 记录详细日志以便调试
        console.log('Error response details:', responseData)
      }

      // 根据是否有成功文件显示不同的提示信息
      const hasSuccessFiles = error.response?.data?.successFiles?.length > 0
      this.$message[hasSuccessFiles ? 'warning' : 'error'](hasSuccessFiles ? '部分文件处理成功' : '文件上传失败！')
      
      // 计算重复记录数
      let duplicateCount = 0
      if (error.response?.data?.duplicateRecords) {
        const fileKeys = Object.keys(error.response.data.duplicateRecords)
        fileKeys.forEach(fileName => {
          const duplicates = error.response.data.duplicateRecords[fileName]
          if (Array.isArray(duplicates)) {
            duplicateCount += duplicates.length
          }
        })
      }
      
      // 构建详细的统计信息
      let summary = ''
      if (error.response?.data) {
        const data = error.response.data
        summary = `共处理 ${data.totalFiles || 0} 个文件，${data.successCount || 0} 个成功，${data.errorCount || 0} 个失败`
        if (data.totalRecords > 0) {
          summary += `\n共 ${data.totalRecords} 条记录，成功保存 ${data.totalSavedCount || 0} 条`
          if (duplicateCount > 0) {
            summary += `，跳过重复记录 ${duplicateCount} 条`
          }
        }
      }
      
      this.uploadResult = {
        success: hasSuccessFiles, // 如果有成功文件，标记为部分成功
        message: errorMessage,
        summary: summary,
        data: errorData,
        details: {
          ...error.response?.data || {},
          duplicateCount: duplicateCount
        }
      }
      console.error('Upload error:', error)
    }
  }
}
</script>

<style scoped>
.transaction-upload {
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.upload-container {
  max-width: 800px;
  margin: 0 auto;
}

.upload-demo {
  border: 2px dashed #dcdfe6;
  border-radius: 6px;
  padding: 40px;
  text-align: center;
  margin-bottom: 40px;
}

.upload-guide {
  margin-bottom: 40px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 6px;
}

.upload-guide h3 {
  margin-bottom: 10px;
  color: #303133;
}

.upload-guide ol {
  padding-left: 20px;
  color: #606266;
}

.upload-guide li {
  margin-bottom: 5px;
}

.upload-result {
  margin-top: 20px;
}

.result-summary {
  margin-top: 20px;
}

.summary-content {
  font-size: 14px;
  line-height: 1.8;
  color: #606266;
  white-space: pre-wrap;
}

.duplicate-details {
  margin-top: 20px;
  background-color: #fafafa;
}

.duplicate-file-section {
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f0f2f5;
  border-radius: 4px;
}

.duplicate-file-section h4 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 15px;
  font-weight: 500;
}

.duplicate-item {
  padding: 8px 0;
  border-bottom: 1px dashed #ebeef5;
  word-break: break-all;
  white-space: normal;
}

.duplicate-item:last-child {
  border-bottom: none;
}

.el-alert {
  margin-bottom: 0;
}

.result-summary .el-card__header {
  padding-bottom: 10px;
}

.duplicate-details .el-card__header {
  background-color: #f5f7fa;
  padding-bottom: 10px;
}
</style>